package cn.jilian.security.web;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import cn.jilian.common.domain.R;
import cn.jilian.common.util.RandomCodes;
import cn.jilian.entity.User;
import cn.jilian.security.util.SessionUtil;
import cn.jilian.security.util.ShiroUtils;


@Controller
@RequestMapping("/login")
public class AuthController {
	
	
	@GetMapping("/")
	public String loginView1() {
		return "login";
	}
	
	@GetMapping("/index.html")
	public String loginView() {
		return "login";
	}

	/**
     * 登录校验
     */
    @PostMapping(value = "/auth")
    @ResponseBody
    public R auth(@RequestParam(value = "username") String username,
                                    @RequestParam(value = "password") String password,
                                    @RequestParam(value = "authCode") String authCode,
                                    HttpSession session) {
       
        String authCode1 = SessionUtil.getAuthCode(session);
        if (!authCode1.equalsIgnoreCase(authCode)) {
            return R.fail("图形验证码验证失败");
        }
        
       User user =null;
        try{
        	 UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
             Subject subject = SecurityUtils.getSubject();
             subject.login(usernamePasswordToken);   //完成登录
             user=(User) subject.getPrincipal();
             SessionUtil.cacheUserInfo(session, user);
        }catch(Exception e){
        	 return R.fail("用户名或密码错误");
        }
        SessionUtil.clearImageCode(session);
        return R.ok("登录成功");
    }
    
    @GetMapping("/logout")
	String logout() {
		ShiroUtils.logout();
		return "redirect:/login/index.html";
	}
    @GetMapping(value = "/vcode")
    public void authCodeImage(HttpServletResponse response, HttpSession session) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            String authCode = RandomStringUtils.randomAlphanumeric(4);
            RandomCodes.drawImage(response.getOutputStream(), authCode);
            SessionUtil.cacheImageAuthCode(session,authCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
